package com.example.d10_homework.homework03;

import java.net.*;
import java.io.*;

public class UDPClient {
    private static final String SERVER_IP = "127.0.0.1"; // 本地测试用
    private static final int SERVER_PORT = 9876;

    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket()) {
            socket.setSoTimeout(1000); // 设置接收的最大等待时间为1秒

            String message = "hello";
            byte[] sendData = message.getBytes();

            for (int i = 0; i < 5; i++) {
                try {
                    DatagramPacket sendPacket = new DatagramPacket(
                            sendData,
                            sendData.length,
                            InetAddress.getByName(SERVER_IP),
                            SERVER_PORT
                    );
                    socket.send(sendPacket);
                    System.out.println("发送: " + message);

                    byte[] receiveData = new byte[256];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    socket.receive(receivePacket); // 可能抛出SocketTimeoutException

                    String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    System.out.println("接收: " + response.trim());

                } catch (SocketTimeoutException ste) {
                    System.out.println("请求超时");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Thread.sleep(1000); // 每次发送后等待1秒
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}